Page({
  data: {
    videoId: null,
    videoDetail: {},
    comments: [],
    relatedVideos: [],
    userInfo: {},
    isLiked: false,
    isCollected: false,
    isFollowed: false,
    isPlaying: false,
    isDescExpanded: false,
    commentText: '',
    sortType: 'time', // time 或 hot
    hasMoreComments: true,
    commentPage: 1,
    loading: false
  },

  onLoad(options) {
    const { id } = options;
    this.setData({
      videoId: id
    });
    
    this.loadUserInfo();
    this.loadVideoDetail(id);
    this.loadComments(id);
    this.loadRelatedVideos(id);
    this.checkUserStatus(id);
  },

  // 加载用户信息
  loadUserInfo() {
    const userInfo = wx.getStorageSync('userInfo') || {
      id: 1,
      name: '美食达人',
      avatar: 'https://picsum.photos/60/60?random=999',
      description: '热爱美食，分享生活'
    };
    this.setData({
      userInfo: userInfo
    });
  },

  // 加载视频详情
  loadVideoDetail(id) {
    this.setData({ loading: true });
    
    // 模拟API请求
    setTimeout(() => {
      const mockDetail = {
        id: id,
        title: '红烧肉制作教程 - 肥而不腻，入口即化的完美做法',
        videoUrl: 'https://sample-videos.com/zip/10/mp4/SampleVideo_1280x720_1mb.mp4',
        coverUrl: 'https://picsum.photos/800/450?random=1',
        views: 123456,
        likes: 5678,
        comments: 234,
        createTime: '2024-01-15',
        authorName: '美食达人',
        authorAvatar: 'https://picsum.photos/60/60?random=1',
        authorFollowers: 12345,
        description: '详细的红烧肉制作步骤，肥而不腻，入口即化。从选料到成品，每个步骤都有详细说明。这道菜的关键在于火候的掌握和调料的配比，按照视频中的方法，你也能做出饭店级别的红烧肉！',
        tags: ['教程', '红烧', '川菜', '家常菜', '下饭菜']
      };

      this.setData({
        videoDetail: mockDetail,
        loading: false
      });
    }, 500);
  },

  // 加载评论
  loadComments(id, page = 1) {
    setTimeout(() => {
      const mockComments = [
        {
          id: 1,
          authorName: '用户A',
          avatar: 'https://picsum.photos/40/40?random=1',
          content: '按照视频做了一次，味道很不错！肥而不腻，入口即化，家人都说好吃！',
          time: '2小时前',
          likes: 12,
          isLiked: false,
          images: [],
          replies: [
            { id: 101, authorName: '美食达人', content: '谢谢支持！' },
            { id: 102, authorName: '用户B', content: '我也试了，确实好吃' }
          ]
        },
        {
          id: 2,
          authorName: '用户B',
          avatar: 'https://picsum.photos/40/40?random=2',
          content: '讲解很详细，学到了很多技巧。特别是炒糖色的部分，以前总是炒糊，现在终于掌握了！',
          time: '5小时前',
          likes: 8,
          isLiked: true,
          images: ['https://picsum.photos/200/200?random=10'],
          replies: []
        },
        {
          id: 3,
          authorName: '用户C',
          avatar: 'https://picsum.photos/40/40?random=3',
          content: '第一次做红烧肉，很成功，感谢分享！按照步骤一步步来，结果很满意。',
          time: '1天前',
          likes: 15,
          isLiked: false,
          images: [],
          replies: []
        }
      ];

      if (page === 1) {
        this.setData({
          comments: mockComments,
          commentPage: 1
        });
      } else {
        this.setData({
          comments: [...this.data.comments, ...mockComments],
          commentPage: page
        });
      }
    }, 800);
  },

  // 加载相关推荐
  loadRelatedVideos(id) {
    setTimeout(() => {
      const mockRelated = [
        {
          id: 101,
          title: '糖醋里脊的做法',
          coverUrl: 'https://picsum.photos/200/150?random=20',
          duration: '4:15',
          views: 45678,
          authorName: '厨艺大师',
          authorAvatar: 'https://picsum.photos/40/40?random=20'
        },
        {
          id: 102,
          title: '宫保鸡丁详细步骤',
          coverUrl: 'https://picsum.photos/200/150?random=21',
          duration: '6:20',
          views: 34567,
          authorName: '川菜师傅',
          authorAvatar: 'https://picsum.photos/40/40?random=21'
        },
        {
          id: 103,
          title: '麻婆豆腐家常做法',
          coverUrl: 'https://picsum.photos/200/150?random=22',
          duration: '5:30',
          views: 23456,
          authorName: '家常菜专家',
          authorAvatar: 'https://picsum.photos/40/40?random=22'
        },
        {
          id: 104,
          title: '水煮鱼的制作方法',
          coverUrl: 'https://picsum.photos/200/150?random=23',
          duration: '7:45',
          views: 56789,
          authorName: '川菜师傅',
          authorAvatar: 'https://picsum.photos/40/40?random=23'
        }
      ];

      this.setData({
        relatedVideos: mockRelated
      });
    }, 1000);
  },

  // 检查用户状态
  checkUserStatus(id) {
    setTimeout(() => {
      this.setData({
        isLiked: Math.random() > 0.5,
        isCollected: Math.random() > 0.5,
        isFollowed: Math.random() > 0.5
      });
    }, 300);
  },

  // 播放视频
  onPlayVideo() {
    this.setData({
      isPlaying: true
    });
  },

  // 点赞
  onLike() {
    const isLiked = !this.data.isLiked;
    const likes = this.data.videoDetail.likes + (isLiked ? 1 : -1);
    
    this.setData({
      isLiked: isLiked,
      'videoDetail.likes': likes
    });

    wx.showToast({
      title: isLiked ? '已点赞' : '已取消点赞',
      icon: 'success'
    });
  },

  // 收藏
  onCollect() {
    const isCollected = !this.data.isCollected;
    
    this.setData({
      isCollected: isCollected
    });

    wx.showToast({
      title: isCollected ? '已收藏' : '已取消收藏',
      icon: 'success'
    });
  },

  // 关注作者
  onFollow() {
    const isFollowed = !this.data.isFollowed;
    
    this.setData({
      isFollowed: isFollowed
    });

    wx.showToast({
      title: isFollowed ? '已关注' : '已取消关注',
      icon: 'success'
    });
  },

  // 评论
  onComment() {
    // 滚动到评论区域
    wx.pageScrollTo({
      selector: '.comments-section',
      duration: 300
    });
  },

  // 评论输入
  onCommentInput(e) {
    this.setData({
      commentText: e.detail.value
    });
  },

  // 提交评论
  onSubmitComment() {
    if (!this.data.commentText.trim()) {
      wx.showToast({
        title: '请输入评论内容',
        icon: 'none'
      });
      return;
    }

    const newComment = {
      id: Date.now(),
      authorName: this.data.userInfo.name,
      avatar: this.data.userInfo.avatar,
      content: this.data.commentText,
      time: '刚刚',
      likes: 0,
      isLiked: false,
      images: [],
      replies: []
    };

    const comments = [newComment, ...this.data.comments];
    const commentCount = this.data.videoDetail.comments + 1;

    this.setData({
      comments: comments,
      'videoDetail.comments': commentCount,
      commentText: ''
    });

    wx.showToast({
      title: '评论成功',
      icon: 'success'
    });
  },

  // 点赞评论
  onLikeComment(e) {
    const commentId = e.currentTarget.dataset.id;
    const comments = this.data.comments.map(comment => {
      if (comment.id === commentId) {
        const isLiked = !comment.isLiked;
        return {
          ...comment,
          isLiked: isLiked,
          likes: comment.likes + (isLiked ? 1 : -1)
        };
      }
      return comment;
    });

    this.setData({
      comments: comments
    });
  },

  // 回复评论
  onReplyComment(e) {
    const commentId = e.currentTarget.dataset.id;
    wx.showModal({
      title: '回复评论',
      editable: true,
      placeholderText: '写下你的回复...',
      success: (res) => {
        if (res.confirm && res.content) {
          wx.showToast({
            title: '回复成功',
            icon: 'success'
          });
        }
      }
    });
  },

  // 分享评论
  onShareComment(e) {
    const commentId = e.currentTarget.dataset.id;
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    });
  },

  // 查看更多回复
  onViewMoreReplies(e) {
    const commentId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/comment-detail/comment-detail?id=${commentId}`
    });
  },

  // 预览图片
  onPreviewImage(e) {
    const urls = e.currentTarget.dataset.urls;
    const current = e.currentTarget.dataset.current;
    wx.previewImage({
      urls: urls,
      current: current
    });
  },

  // 排序评论
  onSortComments() {
    const sortType = this.data.sortType === 'time' ? 'hot' : 'time';
    this.setData({
      sortType: sortType
    });
    
    // 重新加载评论
    this.loadComments(this.data.videoId, 1);
  },

  // 加载更多评论
  onLoadMoreComments() {
    if (this.data.loading) return;
    
    const nextPage = this.data.commentPage + 1;
    this.loadComments(this.data.videoId, nextPage);
  },

  // 切换描述展开状态
  onToggleDesc() {
    this.setData({
      isDescExpanded: !this.data.isDescExpanded
    });
  },

  // 相关推荐点击
  onRelatedTap(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/video-detail/video-detail?id=${id}`
    });
  },

  // 刷新相关推荐
  onRefreshRelated() {
    this.loadRelatedVideos(this.data.videoId);
    wx.showToast({
      title: '已刷新',
      icon: 'success'
    });
  },

  // 分享
  onShare() {
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    });
  },

  // 分享给朋友
  onShareAppMessage() {
    return {
      title: this.data.videoDetail.title,
      path: `/pages/video-detail/video-detail?id=${this.data.videoId}`,
      imageUrl: this.data.videoDetail.coverUrl
    };
  },

  // 分享到朋友圈
  onShareTimeline() {
    return {
      title: this.data.videoDetail.title,
      imageUrl: this.data.videoDetail.coverUrl
    };
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadVideoDetail(this.data.videoId);
    this.loadComments(this.data.videoId, 1);
    this.loadRelatedVideos(this.data.videoId);
    
    setTimeout(() => {
      wx.stopPullDownRefresh();
    }, 1000);
  }
}); 